import { PageContainer } from '@ant-design/pro-layout';
import {  message, Space, Table} from 'antd';
import ProTable, { ActionType } from '@ant-design/pro-table';
import React, { useState} from 'react';
import type { ProColumns } from '@ant-design/pro-table';
import { useRef } from 'react';
import {findSettlementBatch,settleBatch} from './service'
import  {  ModalForm, ProFormDigit} from '@ant-design/pro-form';
import { accAdd, accMul, accSub, manufacturerOption, moneyFormat } from '@/utils/utils';

export default () => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([0]);
  const [activeKey,setActiveKey] = useState("tab1");

  const [proData,setProData] = useState<any>([]);
  const [showDetail, setShowDetail] = useState(false);
  const actionRef = useRef<ActionType>();
 
  const pColumns: ProColumns[] = [
    {
      title: '产品名称',
      width: 120,
      ellipsis:true,
      dataIndex: 'productName',
      editable: false
    }, {
      width: 150,
      ellipsis:true,
      title: '产品型号',
      dataIndex: 'productStandard',
      editable: false
    },{
      title: '订单单价(元)',
      dataIndex: 'price',
      valueType:'money',
      width: 120,
      editable:false,
    },
  ]
  //表头信息以及表值设置
  const columns: ProColumns[] = [
    {
      title:'客户代码',
      dataIndex: 'dealerCode',
      width:100,
    },
    {
      title:'客户名称',
      dataIndex: 'dealerName',
      ellipsis:true,
      width:150,
    },
    {
      title:'订单号',
      dataIndex: 'orderNumber',
      width:120,
    },
    {
      title:'订单日期',
      dataIndex: 'oTime',
      valueType:'dateRange',
      hideInTable:true,
      width:150,
    },
    {
      title: '订单日期',
      dataIndex: 'orderTime',
      width:100,
      hideInSearch:true,
    },
    {
      title: '结算人',
      dataIndex: 'settlementPerson',
      ellipsis:true,
      width:100,
      hideInSearch:activeKey=='tab1',
      hideInTable:activeKey=='tab1',
    },
    {
      title: '结算日期',
      dataIndex: 'settlementTime',
      width:100,
      valueType:'date',
      hideInSearch:activeKey=='tab1',
      hideInTable:activeKey=='tab1',
    },
    {
      title: '产品名称',
      width: 100,
      ellipsis:true,
      dataIndex: 'productName',
      editable: false
    }, {
      width: 120,
      ellipsis:true,
      title: '产品型号',
      dataIndex: 'productStandard',
      editable: false
    },
    {
      title: '订货数量',
      dataIndex: 'orderNum',
      hideInSearch:true,
      editable:false,
      width: 70
    }, {
      title: '订单单价(元)',
      dataIndex: 'price',
      hideInSearch:true,
      width: 90,
      valueType:'money',
      editable:false,
    },
    {
      title: '实际单价(元)',
      dataIndex: 'actualPrice',
      hideInSearch:true,
      width: 90,
      valueType:'money'
    },
    {
      title: '订单总价(元)',
      hideInSearch:true,
      dataIndex: 'o_t_price',
      editable:false,
      width: 90,
      renderText:(text,record:any)=>{
        return '¥'+moneyFormat(accMul(Number(record.price), record.orderNum));
      }
    },
    {
      title: '实际总价(元)',
      dataIndex: 'a_t_price',
      hideInSearch:true,
      editable:false,
      width: 90,
      renderText:(text,record:any)=>{
        if(!record.actualPrice){
          return ''
        }
        return moneyFormat(accMul(Number(record.actualPrice), record.orderNum));
      }
    },
    {
      title: '订单差价(元)',
      dataIndex: 'differenceAmount',
      hideInSearch:true,
      editable:false,
      width: 90,
      valueType:'money'
    },
    {
      title: '返利金额(元)',
      editable:false,
      hideInSearch:true,
      valueType:'money',
      dataIndex: 'refundAmount',
      width: 90,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInSearch:true,
      width: 200,
      ellipsis:true,
    },
  ];
  
  return (
    <PageContainer>
    <ProTable
      headerTitle=''
      pagination={{
        pageSizeOptions:['20', '100', '500']
      }}
      actionRef={actionRef}
      tableAlertOptionRender={activeKey=='tab1'?({selectedRowKeys,selectedRows,onCleanSelected}) => {
        return (
          <Space size={16}>
            <a key="i2" style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
            <a key="i1" onClick={()=>{
                  if(selectedRows.length>0){
                    for(var i=1;i<selectedRows.length;i++){
                      if(selectedRows[i].productStandard!=selectedRows[0].productStandard||selectedRows[i].price!=selectedRows[0].price){
                          message.warn('请勾选产品型号、价格一致的数据')
                          return 
                      }
                    }
                  }
                  setProData(selectedRows)
                  setShowDetail(true)
            }}>批量结算</a>
          </Space>
        );
      }:false}
      rowSelection={{
        selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
      }}
      scroll={{x:activeKey=='tab1'?1800:1900}}
      request ={async(params, sorter, filter) => {
       if(activeKey=='tab1'){
          params.settled = 'false'
        }else{
          params.settled = 'true'
        }
        if(params.oTime&&params.oTime.length>0){
          params.orderBeginTime = params.oTime[0]
          params.orderEndTime = params.oTime[1]
          params.oTime = undefined;
        }
        return findSettlementBatch({ ...params, sorter, filter })
      }}
      columns={columns}
      rowKey="settlementDetailId"
      search={{span:6}}
      toolbar={{
        menu: {
          type: 'tab',
          activeKey: activeKey,
          items: [
            {
              key: 'tab1',
              label: <span>未结算</span>,
            },
            {
              key: 'tab2',
              label: <span>已结算</span>,
            },
          ],
          onChange: (key) => {
            setActiveKey(key as string);
            actionRef.current?.reloadAndRest?.();
          },
        },
        settings: [],
      }}
      />
      
       <ModalForm title='批量结算' width={1200} visible={showDetail}  onVisibleChange={v=>{setShowDetail(v)}}
       onFinish={async(value)=>{
        value.productId = proData[0].productId
        value.price = proData[0].price
        value.settlementIds = proData.map((item:any)=>item.settlementId)
        var val =await settleBatch(value)
        if (val.errorCode === '200') {
          message.success('结算成功')
          actionRef.current?.reloadAndRest?.();
          return true
        }else{
          message.error(val.errorMessage);
          return false
        }
  
       }}
        modalProps={{
          destroyOnClose:true,
          forceRender:true
        }}>
        <ProTable  headerTitle="" rowKey='settlementDetailId' columns={pColumns} dataSource={proData} search={false} toolbar={{
            settings: []
        }} pagination={false} />
        <div style={{margin:20}}>
           <ProFormDigit width='md' rules={[{ required: true}]} min={0} name="actualPrice" label="实际单价" placeholder="请输入实际单价"/>
        </div>
       
        </ModalForm>
       
      
  </PageContainer>
  );
};